<template>
  <div>
    <el-form :model="searchList" ref="searchList">
      <el-row :gutter="20">
        <el-col :span="4" :offset="0">
          <el-form-item label>
            <el-select
                v-model="searchList.apply_batch"
                value-key="apply_batch"
                placeholder="申报批次"
                clearable >
              <el-option
                  v-for="item in apply_batch_list"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4" :offset="0">
          <el-form-item label>
            <el-select
              v-model="searchList.data_status"
              value-key="data_status"
              placeholder="数据状态"
              clearable
            >
              <el-option
                  v-for="item in data_status_list"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="9" :offset="0">
          <div class="right">
            <el-button type="primary" size="medium" @click="search" :loading="loading">查询</el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <el-table :data="tableData.results" border stripe :height="offsetHeight" v-loading="loading">
      <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
      <el-table-column prop="apply_batch" label="申报批次" min-width="100" align="center"></el-table-column>
      <el-table-column
        prop="third_check_company_name"
        label="咨询机构名称"
        min-width="200"
        align="center"
      ></el-table-column>
      <el-table-column label="需求确认书状态" width="200" align="center">
        <template slot-scope="{row}" v-if="row.issue_status">
          <el-tag type="success" size="medium" v-if="row.issue_status ==='000'">咨询机构未生成</el-tag>
          <el-tag type="warning" size="medium" v-else-if="row.issue_status ==='00'">咨询机构未上传</el-tag>
          <el-tag type="warning" size="medium" v-else-if="row.issue_status ==='0'">咨询机构未下发</el-tag>
          <el-tag type="warning" size="medium" v-else-if="row.issue_status ==='1'">申报单位未上传</el-tag>
          <el-tag type="warning" size="medium" v-else-if="row.issue_status ==='2'">申报单位未确认</el-tag>
          <el-tag type="warning" size="medium" v-else-if="row.issue_status ==='3'">咨询机构未审批</el-tag>
          <el-tag type="warning" size="medium" v-else-if="row.issue_status ==='4'">已审批通过</el-tag>
          <el-tag type="warning" size="medium" v-else-if="row.issue_status ==='5'">已驳回</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="issue_date" label="下发时间" min-width="100" align="center"></el-table-column>
      <el-table-column prop="upload_date" label="回传时间" min-width="100" align="center"></el-table-column>
      <el-table-column prop="examine_date" label="审核时间" min-width="100" align="center"></el-table-column>
      <el-table-column prop="reason" label="驳回原因" width="150" align="center"></el-table-column>
      <el-table-column label="数据状态" width="150" align="center">
        <template slot-scope="{row}" v-if="row.data_status">
          <el-tag type="warning" size="medium" v-if="row.data_status ==='1'">当前</el-tag>
          <el-tag type="warning" size="medium" v-else-if="row.data_status ==='0'">历史</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="350" fixed="right" align="center">
        <template slot-scope="{row}">
          <el-row type="flex" justify="center" style="margin: auto 0;">
            <el-button
              type="primary"
              size="mini"
              @click="exportItem(row.confirmmation_file)"
              v-if="row.confirmmation_file.length>0 &&(row.issue_status ==='1'||row.issue_status ==='2'||row.issue_status ==='3'||row.issue_status ==='4'||row.issue_status ==='5')"
            >下载下发</el-button>

            <el-upload
              style="margin-left: 10px;"
              class="upload-demo"
              action
              :http-request="httpRequest"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-upload="handleBeforeUpload"
              multiple
              :limit="1"
              :on-exceed="handleExceed"
              accept=".pdf,.rar,.zip"
              :show-file-list="false"
              v-if="row.issue_status ==='1' || row.issue_status ==='2'"
            >
              <el-button type="primary" size="mini" @click="contractInfo(row)">回传</el-button>
            </el-upload>

            <el-button
              style="margin-left: 10px;"
              type="primary"
              size="mini"
              v-if="row.confirmmation_file_apply"
              @click="exportPdf(row.confirmmation_file_apply)"
            >查看回传</el-button>

            <!-- row.issue_status ==='2' -->

            <el-button
              v-if="row.issue_status ==='2'"
              type="primary"
              size="mini"
              @click="confirmStatus(row)"
              style="margin-left: 10px;"
            >确认</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <div class="page">
      <el-pagination
        @size-change="pageSizeChange"
        @current-change="pageNoChange"
        :page-sizes="[10, 50, 100, 200]"
        :page-size="10"
        background
        layout="total, sizes, prev, pager, next"
        :total="tableData.totalRecord"
      ></el-pagination>
    </div>
    <!-- 报告导出模板 -->
    <requirement-report ref="requirementReport" v-show="false" @outData="receiveData"></requirement-report>
  </div>
</template>
<script>
import axios from 'axios'
import ProjectItem from '@/components/Project'
import FlowItem from '@/components/FlowChart'
import { issue_status_list,apply_batch_list,data_status_list,d_buildType } from '@/utils/dicts.js'
import RequirementReport from '@/components/Report/RequirementReport'
import { mapGetters } from "vuex";
export default {
  name: 'requirementSheet',
  components: {
    ProjectItem, FlowItem, RequirementReport
  },
  props: {
    switch: {
      type: Boolean,
      default: () => {
        return true
      }
    },
  },
  data () {
    return {
      fileList: [],
      global_project_id: '',
      offsetHeight: document.documentElement.clientHeight - 260,
      searchList: {
        data_status: '1'
      },
      loading: false,
      saveLoading: false,
      tableData: [],
      projectShow: false,
      projectParams: {},
      d_buildType: d_buildType,
      apply_batch_list: apply_batch_list,
      data_status_list: data_status_list,
      flowShow: false,
      flowParams: {},
      showAll: false,
      pageNo: '1',
      pageSize: '10'
    }
  },
  created () {
  },
  mounted () {
  },
  methods: {
    receiveData (file) {
      let fileName = ''
      // let point = file.file.name.lastIndexOf('.')
      const timestamp = new Date().getTime();
      const random = Math.floor(Math.random() * 999999);
      // 时间戳 + 6位随机数
      fileName = timestamp.toString()
      const res = this.$http('uploadSign', {
        fileName: fileName,
        filePath: 'house/Wl',
        timestamp: timestamp
      })

      const sign = res.sign
      let reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = async (e) => {
        this.loading = true
        const file = e.target.result.substring(e.target.result.indexOf(',') + 1);
        const res1 = this.$http('downloadPdf', {
          file: file,
        })
        console.log(res1)
        if (res1) {
          let httpType = 'application/pdf';
          let url = window.URL.createObjectURL(
            new Blob([res1.data], {
              type: httpType
            })
          );
          //创建隐藏的a标签
          let link = document.createElement("a");
          link.style.display = "none";
          link.href = url;
          //设置导出文件的名字
          let excelName = "需求确认书.pdf";
          link.setAttribute("download", excelName);
          document.body.appendChild(link);
          //模拟点击事件
          link.click();
          //导出成功后删除这个标签并释放blob对象
          link.remove();
          window.URL.revokeObjectURL(url); //释放掉blob对象
          this.$message.success(`导出成功！`);
          setTimeout(() => {
            this.loading = false;
          }, 500);
        } else {
          this.loading = false
          return
        }
        this.loading = false
      }
    },
    confirmStatus (row) {
      this.$http('cofirmRequirementFromApply', {
        id: row.id
      }).then(res => {
        this.init()
      })
    },
    async httpRequest (file) {
      let fileName = ''
      let point = file.file.name.lastIndexOf('.')
      const timestamp = new Date().getTime();
      const random = Math.floor(Math.random() * 999999);
      // 时间戳 + 6位随机数
      fileName = timestamp + random + file.file.name.slice(point, file.file.name.length)
      const res = await this.$http('uploadSign', {
        fileName: fileName,
        filePath: 'house/Wl',
        timestamp: timestamp
      })
      const sign = res.sign
      let reader = new FileReader();
      reader.readAsDataURL(file.file);
      reader.onload = async (e) => {
        this.loading = true
        const file = e.target.result.substring(e.target.result.indexOf(',') + 1);
        const res1 = await this.$http('uploadBase', {
          fileName: fileName,
          filePath: 'house/Wl',
          timestamp: timestamp,
          sign: sign,
          file: file,
        })
        if (res1) {
          this.$http('uploadRequirementFromApply', {
            id: this.flowParams.id,
            confirmmation_file_apply: res1
          }).then(res => {
            this.loading = false
            this.$message.success('上传成功');
            this.init()
          })

        } else {
          this.loading = false
          return
        }
        this.loading = false
      }
    },
    handleRemove (file, fileList) {
      console.log(file, fileList);
    },
    handlePreview (file) {
      console.log(file);
      // if(file.fileName.indexOf("pdf") ==-1) {
      //   this.$tips.error('上传文件只能是 pdf 格式')
      //   return
      // }
    },
    handleExceed (files, fileList) {
      // this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    handleBeforeUpload (file) {
      console.log('file===', file)
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      console.log('testmsg===', testmsg)
      // .jpg,.jpeg,.png,.pdf,.PDF
      const extension4 = testmsg === 'pdf'
      const extension5 = testmsg === 'PDF'
      const extension6 = testmsg === 'rar'
      const extension7 = testmsg === 'zip'
      if (!extension4 && !extension5&& !extension6&& !extension7) {
        this.$message({
          message: '上传文件只能是 .pdf、.PDF、.rar、.zip !',
          type: 'warning'
        })
        return false
      } else {
        return true
      }
    },
    contractInfo (row) {
      this.flowParams = row
    },
    orderNoChange () {
      this.$forceUpdate();
    },
    clearInput () {
      this.showAll = true
      this.searchList.apply_batch = ''
      this.searchList.project_name = ''
    },
    async init () {
      this.loading = true
        this.$http('findListForApplyCompany', {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          apply_company_code: this.user.company_code,
          ...this.searchList
        }).then(res => {
          this.tableData = res
          this.loading = false
        })
    },
    isEmpty (obj) {
      if (typeof obj == "undefined" || obj == null || obj === '') {
        return true;
      } else {
        return false;
      }

    },
    search () {
      this.init()
    },
    pageNoChange (pageNo) {
      this.pageNo = pageNo
      this.init()
    },
    pageSizeChange (pageSize) {
      this.pageSize = pageSize
      this.init()
    },
    exportExcel () {
      this.saveLoading = true
      window.open('/api/ac/maintain/excelServiceImpl/exportInfoExcelData')
      this.saveLoading = false
    },
    exportPdf (url) {
      //导出需求确认书
      this.saveLoading = true
      window.open(url)
      this.saveLoading = false
    },
    exportItem (ossurl) {
      // this.loading = true
      //调用后端接口输出
      axios({
        method: 'get',
        url: '/api/ac/maintain/requirementConfirmationSheetService/downpdf?ossUrl=' + ossurl,
        data: '',
        responseType: "blob"
      }).then(res => {
        const link = document.createElement("a");
        let blob = new Blob([res.data], { type: "application/pdf" });
        link.style.display = "none";
        link.href = URL.createObjectURL(blob);
        link.setAttribute("download", "需求确认书.pdf");
        document.body.appendChild(link);
        link.click();
        this.loading = false
        document.body.removeChile(link);
      })

    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
}
</script>
<style scoped>
</style>
